package com.jiayi.weiphoto.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.ContentHandler;
import java.net.ContentHandlerFactory;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import com.jiayi.weiphoto.activity.AppStartGradual;
import com.jiayi.weiphoto.activity.MainConstants;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.graphics.Rect;
import android.os.Environment;
import android.util.StringBuilderPrinter;


public class HttpUtil {
	
	final static int TIME_OUT = 8000;
	
	public static void postMethod(String url, HashMap<String, String> params, HttpResListener httpResListener) throws ClientProtocolException, IOException{
		HttpClient client = new DefaultHttpClient();
		HttpPost postMethod = new HttpPost(url);
		ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		if(params != null){
			for(String key: params.keySet()){
				nameValues.add(new BasicNameValuePair(key, params.get(key)));
			}
		}
		HttpEntity entity = new UrlEncodedFormEntity(nameValues);
		postMethod.setEntity(entity);
		HttpResponse response = client.execute(postMethod);
		if(httpResListener != null)
			httpResListener.onRes(response, params, url);
	}
	
	public static void postMethod(String url, HashMap<String, String> params) throws ClientProtocolException, IOException{
		postMethod(url, params, null);
	}
	
	public static String strPostMethod(String url, HashMap<String, String> params) throws ClientProtocolException, IOException {
		String msg = "";
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
		HttpPost postMethod = new HttpPost(url);
		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		if(params != null){
			for(String key: params.keySet()){
				pairs.add(new BasicNameValuePair(key, params.get(key)));
			}
		}
		HttpEntity entity = new UrlEncodedFormEntity(pairs);
		postMethod.setEntity(entity);
		HttpResponse response = client.execute(postMethod);
		msg = getResponseMsg(response);
		return msg;
	}
	
	public static String getMethod(String url, HashMap<String, String> params){
		String paramsPart = "?";
		for(String key : params.keySet()){
			paramsPart += key+"="+params.get(key)+"&";
		}
		String reQuestUrl = url+paramsPart;
		MyLog.d("request url is ===>"+reQuestUrl);
		String msg = "";
		try {
			msg = getUrlMessage(reQuestUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return msg;
	}
	
	public static String getUrlMessage(String urlStr) throws Exception{
		String msg = "";
		HttpGet httpGet = new HttpGet(urlStr);
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
		HttpResponse response = client.execute(httpGet);
		HttpEntity entity = response.getEntity();
		BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
		InputStream i = (InputStream) bufferedEntity.getContent();
		BufferedInputStream bis = new BufferedInputStream(i);
		byte[] buffer = new byte[10240];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		while((len = bis.read(buffer)) != -1){
			bos.write(buffer, 0, len);
		}
		msg = new String(bos.toByteArray(), "UTF-8");
		return msg;
	}
	
	public static String getResponseMsg(HttpResponse response) throws IllegalStateException, IOException{
		String msg = "";
		BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
		BufferedReader reader = new BufferedReader(new InputStreamReader(bis));
		String line = "";
		while((line = reader.readLine()) != null){
			msg += line;
		}
		reader.close();
		bis.close();
		return msg;
	}
	
	public static byte[] getUrlContent(String urlStr){
		byte[] res = null;
		URL url;
		try {
			url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.connect();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			byte[] buffer = new byte[1000];
			int len = 0;
			while((len = bis.read(buffer)) != -1){
				bos.write(buffer, 0, len);
			}
			bos.flush();
			bis.close();
			res = bos.toByteArray();
			bos.close();
			conn.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
	
	public static synchronized Bitmap getBitmap(String urlStr){
		if(urlStr == null || urlStr.length() == 0) return null;
		Bitmap bitmap = null;
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			if(!FileUtil.isExist(MainConstants.IMAGE_CACHE)){
				FileUtil.createADir(MainConstants.IMAGE_CACHE);
			}
			File bFile = new File(MainConstants.IMAGE_CACHE+MD5.getMD5(urlStr));
			try {
				if(bFile.exists()){
					FileInputStream finputStream = new FileInputStream(bFile);
						bitmap = getBitmapByInputStream(finputStream);
						finputStream.close();
						return bitmap;
				}
				bFile.createNewFile();
				HttpGet httpGet = new HttpGet(urlStr);
				HttpClient client = new DefaultHttpClient();
				MyLog.e("bitmap url is "+urlStr);
				HttpResponse response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
				InputStream i = (InputStream) bufferedEntity.getContent();
				FileOutputStream out = new FileOutputStream(bFile);
				bitmap = BitmapFactory.decodeStream(i);
				if(bitmap != null){
					bitmap.compress(CompressFormat.JPEG, 75, out);
				}
				out.flush();
				i.close();
				out.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				URL url = new URL(urlStr);
				InputStream i = (InputStream) url.getContent();
				bitmap = BitmapFactory.decodeStream(i);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bitmap;
	}
	
	public static Bitmap getBitmap(String urlStr,String filePath){
		Bitmap bitmap = null;
		if(urlStr == null || urlStr.length() == 0) return null;
//		BitmapFactory.Options opts = new BitmapFactory.Options();
//		opts.inPreferredConfig = Config.RGB_565;
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			if(!FileUtil.isExist(filePath)){
				FileUtil.createADir(filePath);
			}
			File bFile = new File(filePath+MD5.getMD5(urlStr));
//			File sFile = FileUtil.getResizedBitmapFile(bFile);
			try {
				if(bFile.exists()){
					FileInputStream finputStream = new FileInputStream(bFile);
//						bitmap = getBitmapByInputStream(finputStream);
					bitmap = BitmapFactory.decodeStream(finputStream);
//					BitmapFactory.decodeStream(finputStream, null, opts);
						finputStream.close();
						return bitmap;
				}
				HttpGet httpGet = new HttpGet(urlStr);
				HttpClient client = new DefaultHttpClient();
				MyLog.e("bitmap url is "+urlStr);
				HttpResponse response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
				InputStream i = (InputStream) bufferedEntity.getContent();
				bitmap = BitmapFactory.decodeStream(i);
				if(bitmap != null){
					bFile.createNewFile();
					FileOutputStream out = new FileOutputStream(bFile);
					bitmap.compress(CompressFormat.JPEG, 75, out);
					out.flush();
					i.close();
					out.close();
				}else{
					bFile.delete();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				URL url = new URL(urlStr);
				InputStream i = (InputStream) url.getContent();
				bitmap = BitmapFactory.decodeStream(i);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		Bitmap resizedBitmap = ImageUtil.getInstance().resizeBitmap(bitmap, AppStartGradual.screenWidth, AppStartGradual.screenHeight);
		return bitmap;
	}
	
	private static Bitmap getBitmapByInputStream(InputStream in) throws IOException{
		Bitmap bitmap ;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int size = 0;
		while((size = in.read(buffer)) != -1){
			bos.write(buffer, 0, size);
		}
		byte[] bytes = bos.toByteArray();
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		in.close();
		return bitmap;
	}
	
	private static InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    public static Bitmap get1Bitmap(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;
    }
    
    public Bitmap loadBitmap(String filePath){
		Bitmap bitmap = null;
		File picFile = new File(filePath);
		if(picFile.exists()){
			try {
				FileInputStream fis = new FileInputStream(picFile);
				bitmap = BitmapFactory.decodeStream(fis);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return bitmap;
		}
		return null;
	}
	
    
	public static String getBaiduPanDownloadUrl(String url){
			String msg = "";
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, 20000);
			HttpConnectionParams.setSoTimeout(params, 30000);
			HttpConnectionParams.setSocketBufferSize(params, 10240);
			HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.26) Gecko/20120128 Firefox/3.6.26");
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			HttpClient client = new DefaultHttpClient(params);
			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader("x-requested-with", "XMLHttpRequest");
			httpGet.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
			httpGet.addHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
			try {
				HttpResponse response = client.execute(httpGet);
				if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_PARTIAL){
					HttpEntity entity = response.getEntity();
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					int len = 0;
					byte[] buffer = new byte[1024];
					BufferedInputStream bis = new BufferedInputStream(entity.getContent());
					while((len = bis.read(buffer)) != -1){
						bos.write(buffer, 0, len);
					}
					bos.flush();
					bos.close();
					bis.close();
					byte[] res = bos.toByteArray();
					String html = new String(res, "utf-8");
					Pattern p = Pattern.compile("(?<=(<a class=\"new-dbtn\" href=\"" + "))[.\\s\\S]*?(?=(" + "\" id=\"downFileButtom\">))");
					Matcher matcher = p.matcher(html);
					if(matcher.find()){
						msg = matcher.group(0).replace("&amp;", "&");
					}
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return msg;
	}
	
	public static File downloadImg(String urlStr, String rootPath){
		File imgFile = new File(rootPath+MD5.getMD5(urlStr));
		if(!imgFile.exists()){
			try {
				FileUtil.makeFile(imgFile.getAbsolutePath());
				FileOutputStream fos = new FileOutputStream(imgFile);
				URL url = new URL(urlStr);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				conn.connect();
				BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
				byte[] buffer = new byte[1000];
				int len = 0;
				while((len = bis.read(buffer)) != -1){
					fos.write(buffer, 0, len);
				}
				fos.flush();
				bis.close();
				fos.close();
				conn.disconnect();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return imgFile;
	}
	
	public interface HttpResListener{
		public void onRes(HttpResponse response, HashMap<String, String> params, String url);
	}
	
	public interface HttpMsgListener{
		public void onMsg(String msg);
	}

	public static void downloadBigBitmap(String urlStr, String rootPath) {
		// TODO Auto-generated method stub
		
	}
	
}
